<?php

declare(strict_types=1);

namespace app\api\controller;

use app\api\validate\User;
use app\BaseController;
use app\common\lib\Show;
use think\facade\Cache;

/**
 * 前端登录 redis+token
 * Class Login
 * @package app\api\controller
 */
class Login extends BaseController
{

    /**
     * 小程序登录
     * @return \think\response\Json
     */
    public function index()
    {
        if (!$this->request->isPost()) {
            return Show::error([],"非法请求");
        }

        $jsCode = $this->request->param("code", "", "trim"); //wx.login()获取的code
        //参数校验
        $data = [
            'js_code' => $jsCode,
        ];
        $validate = new User();
        if (!$validate->scene('wechat_login')->check($data)) {
            return Show::error([], $validate->getError());
        }
        try {
            $result = (new \app\common\business\User())->login($data); //此处login不是静态方法，需要实例化对象调用
        } catch (\Exception $e) {
            return Show::error([], $e->getMessage(), $e->getCode());
        }
        if ($result) {
            return Show::success($result, "登录成功");
        }
        return Show::error([], "登录失败");
    }
}
